<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/modules/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import chatService from '@/services/chatService'

const conversations = ref([])
const router = useRouter()
const authStore = useAuthStore()
const selectedItems = ref([]) // 存储被选中的会话ID
const { username } = authStore.user

// 删除选中的会话
const deleteSelected = async () => {
  if (selectedItems.value.length === 0) return
  try {
    const confirmDelete = await ElMessageBox.confirm(
      `确定要删除所选的 ${selectedItems.value.length} 个对话吗？删除后无法恢复。`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'save-button',
        cancelButtonClass: 'cancel-button',
        type: 'warning'
      }
    ).catch(() => false)

    if (!confirmDelete) return
    const chatIds = selectedItems.value.map((item) => item.id)
    const response = await chatService.deleteMultipleConversations(chatIds)

    if (!response.success) {
      throw new Error(response.message || '删除失败')
    }

    conversations.value = conversations.value.filter(
      (conv) => !selectedItems.value.includes(conv.id)
    )
    selectedItems.value = []
    ElMessage.success('批量删除成功')
    await nextTick()
    handleRefresh()
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error(`批量删除失败: ${error.message}`)
  }
}

// 删除单个会话
const deleteConversation = async (chatId) => {
  try {
    const confirmDelete = await ElMessageBox.confirm(
      '确定要删除此对话吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'save-button',
        cancelButtonClass: 'cancel-button',
        type: 'warning'
      }
    ).catch(() => false)

    if (!confirmDelete) return

    const response = await chatService.deleteConversation(chatId)

    if (!response.success) {
      throw new Error(response.message || '删除失败')
    }

    conversations.value = conversations.value.filter((conv) => conv.id !== chatId)
    const index = selectedItems.value.indexOf(chatId)
    if (index !== -1) {
      selectedItems.value.splice(index, 1)
    }

    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error(`删除失败: ${error.message}`)
  }
}

// 获取历史聊天记录
const fetchChatHistory = async () => {
  try {
    const data = await chatService.getChatHistory()
    if (data && data.length > 0) {
      // 过滤掉没有消息内容的对话
      const filteredConversations = data.filter((conv) => {
        return conv.messages && Array.isArray(conv.messages) && conv.messages.length > 0
      })

      conversations.value = filteredConversations.map((conv) => {
        let userMessage = '无消息内容'

        if (conv.messages && Array.isArray(conv.messages)) {
          const firstUserMsg = conv.messages.find((msg) => msg.role === 'user')
          if (firstUserMsg && firstUserMsg.content) {
            userMessage = firstUserMsg.content
          }
        }

        const preview = userMessage.length > 15 ? userMessage.substring(0, 15) + '...' : userMessage

        return {
          ...conv,
          preview,
          displayTitle: preview
        }
      })
      console.log(conversations.value, 'conversations.value')
    } else {
      console.log('没有聊天历史或数据格式不正确')
    }
  } catch (error) {
    console.error('获取聊天记录失败:', error)
    ElMessage.error('获取聊天记录失败')
  }
}

// 格式化时间函数
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return '未知时间'
    return date.toLocaleString('zh-CN')
  } catch (error) {
    console.error('日期格式化出错:', error, dateString)
    return '未知时间'
  }
}

// 跳转到聊天详情
const goToChat = (chatId) => {
  // 将聊天ID存储到localStorage，以便Chat.vue可以获取
  localStorage.setItem('selectedChatId', chatId)
  router.push({
    name: 'chat',
    query: { id: chatId } // 通过query参数传递ID
  })
}
// 删除多个对话存储对话 ID
const handleSelectionChange = (newSelection) => {
  selectedItems.value = newSelection
}
// 刷新
const handleRefresh = () => {
  fetchChatHistory()
}
onMounted(() => {
  if (authStore.isAuthenticated) {
    fetchChatHistory()
  }
})
</script>

<template>
  <div class="history-container">
    <h2>对话历史</h2>
    <el-card style="border: none; margin-top: 30px">
      <el-form style="display: flex; justify-content:flex-end">

        <el-form-item>
          <el-button class="cancel-button refresh-button" @click="handleRefresh">刷新</el-button>
          <el-button class="cancel-button delete-button" @click="deleteSelected">删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-table
      :data="conversations"
      style="width: 100%; margin-top: 30px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" prop="id" width="55" />
      <el-table-column label="用户名" width="80">
        {{ username }}
      </el-table-column>
      <el-table-column label="对话内容" prop="displayTitle" width="240" show-overflow-tooltip />
      <el-table-column label="创建时间">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间">
        <template #default="scope">
          {{ formatDate(scope.row.updated_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="goToChat(scope.row.messages[0].chat_id)"
            >跳转</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="deleteConversation(scope.row.messages[0].chat_id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.history-container {
  padding: 20px;
  max-width: 960px;
  margin: 0 auto;
}

/* 工具栏样式 */
.history-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
  padding: 10px;
  background: var(--color-background-soft);
  border-radius: 8px;
}

.selection-info {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.toolbar-actions {
  display: flex;
  gap: 10px;
}

.toolbar-btn {
  padding: 6px 12px;
  border-radius: 4px;
  background: transparent;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.toolbar-btn:hover:not(:disabled) {
  background: var(--menu-hover-bg);
  color: var(--menu-text-hover-color);
}

.toolbar-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.delete-btn {
  color: #f56c6c;
}
.select-btn {
  color: var(--color-text);
}

.conversation-list {
  margin-top: 20px;
}

.conversation-item {
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
  background: var(--color-background-soft);
  cursor: pointer;
  display: flex;
  align-items: center;
  position: relative;
}

.conversation-select {
  margin-right: 15px;
  display: flex;
  align-items: center;
}

.conversation-select input[type='checkbox'] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.conversation-content {
  flex: 1;
  min-width: 0; /* 确保内容可以适当缩小 */
}

.conversation-actions {
  margin-left: 10px;
}

.conversation-delete-btn {
  background: transparent;
  border: none;
  color: var(--el-text-color-regular);
  padding: 5px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.6;
  transition: all 0.2s;
}

.conversation-delete-btn:hover {
  color: #f56c6c;
  opacity: 1;
  background-color: rgba(245, 108, 108, 0.1);
}

.conversation-item:hover {
  background: var(--menu-hover-bg);
}

.conversation-item:hover .conversation-preview,
.conversation-item:hover h3,
.conversation-item:hover .conversation-date {
  color: var(--menu-text-hover-color);
}
.conversation-item:hover .conversation-delete-btn {
  color: #f56c6c;
  opacity: 1;
}
h3 {
  margin: 0;
  margin-bottom: 5px;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-date {
  font-size: 0.9em;
  color: var(--el-text-color-regular);
  margin: 5px 0;
}

.conversation-preview {
  color: var(--el-text-color-regular);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin: 0;
}

.no-records {
  margin-top: 30px;
  text-align: center;
  font-size: 16px;
  color: var(--el-text-color-secondary);
}

:deep(.el-table__body-wrapper) {
  background: var(--color-background-soft) !important;
}
:deep(.el-card) {
  background: var(--color-background-soft) !important;
}
:deep(.el-input__wrapper) {
  background: var(--el-fill-color-light) !important;
  box-shadow: none !important;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap !important;
}
</style>

<style>
.cancel-button,
.save-button {
  background: transparent;
  border: none;
  color: var(--el-button-save-text-color);
}

.cancel-button {
  color: var(--el-button-cancel-text-color);
}

.cancel-button:hover {
  background: var(--el-button-cancel-hover-color);
  color: var(--el-button-cancel-hover-text-color) !important;
}

.save-button:hover {
  background: var(--el-button-save-hover-color);
  color: var(--el-button-save-hover-text-color);
}
</style>
